﻿@page "/Admin/Users"
@attribute [Authorize]
@attribute [TabItemOption(Text ="用户管理",Icon ="fa fa-th")]
@inherits BasePage
@inject DialogService DialogService
@inject ISysOrgService SysOrgService
@inject ISysUserService SysUserService
@inject ISysRoleService SysRoleService

<div class="row h-100 overflow-hidden">
    <div class="col-2 h-100">
        <Card class ="h-100">
            <CardHeader>机构层级</CardHeader>
            <CardBody>
                <AsyncRender 
                    OnQueryAsync="SysOrgService.GetTreeOrgsAsync" 
                    OnAfterQuery="((vs)=>_allOrgs = vs)">
                    <Tree Items="context" OnTreeItemClick="OnOrgTreeItemClick"></Tree>
                </AsyncRender>
            </CardBody>
        </Card>
    </div>

    <div class="col-10 h-100">
        <Table TItem="UserOutput"
                @ref = "@_table"
                IsPagination="true"
                IsStriped="true"
                IsMultipleSelect="true"
                IsBordered="false"
                IsFixedHeader="true" 
                AllowResizing="true"
                ShowLoading="true"
                ShowColumnList="true"
                ShowCardView="true"
                ShowToolbar="true"
                ShowSearch="true"
                ShowExtendButtons="true" 
                ShowEmpty="true" 
                SearchModel="@_search" 
                SearchMode="SearchMode.Top"
                EditDialogItemsPerRow="1"
                EditDialogSize="Size.Medium"
                ExtendButtonColumnWidth="195"
                PageItemsSource="@(new int[] { 15, 50 })"
                OnQueryAsync="@OnQueryAsync"
                OnSaveAsync="@OnSaveAsync"
                OnDeleteAsync="@OnDeleteAsync">
            <TableColumns>
                <TableColumn @bind-Field="@context.Account" />
                <TableColumn @bind-Field="@context.Name" />
                <TableColumn @bind-Field="@context.Sex"/>
                <TableColumn @bind-Field="@context.Phone" />
                <TableColumn @bind-Field="@context.Status"/>
            </TableColumns>
            <EditTemplate>
                    <div class="row g-3 form-inline">
                        <div class="col-sm-6">
                            <BootstrapInput @bind-Value="@context.Name" maxlength="50" />
                        </div>
                    </div>
            </EditTemplate>
            <RowButtonTemplate>
                <DropdownButton Text="更多" 
                    Items="@(new List<DropdownButtonItem>()
                    {
                        new("重置密码",()=> OnResetPwdAsync(context),"确认重置选中行的密码？"),
                        new("授权角色",()=> OnOwnRoleAsync(context)),
                        new("授权数据",()=> OnOwnDataAsync(context)),
                    })"/>
            </RowButtonTemplate>
            <SearchTemplate>
                <GroupBox Title="搜索条件">
                    <div class="row g-3 form-inline">
                        <div class="col-12 col-sm-6">
                            <BootstrapInput @bind-Value="@context.Name" ShowLabel="true"/>
                        </div>
                    </div>
                </GroupBox>
            </SearchTemplate>
        </Table>
    </div>
</div>


@code{
    private Table<UserOutput>? _table;
    private UserOutput _search = new();
    private string? _selectOrg;
    private List<RoleOutput>? _allRoles = new();
    private List<RoleOutput> _ownRoles = new();
    private List<TreeItem> _allOrgs = new();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            _allRoles = await SysRoleService.DropDownAsync();
        }
    }

    private Task<QueryData<UserOutput>> OnQueryAsync(QueryPageOptions options)
    {
        var search = _search.Adapt<UserPageInput>(options);
        search.SysEmpParam.OrgId = _selectOrg;
        return SysUserService.PageAsync(search);
    }

    private Task<bool> OnDeleteAsync(IEnumerable<UserOutput> items) 
        => SysUserService.DeleteAsync(items);

    private async Task<bool> OnSaveAsync(UserOutput item, ItemChangedType type)
    {
        var result = false;
        switch (type)
        {
            case ItemChangedType.Add:
                result = await SysUserService.AddAsync(item);
                break;
            case ItemChangedType.Update:
                result = await SysUserService.EditAsync(item);
                break;
        }
        return result;
    }

    private async Task OnResetPwdAsync(UserOutput item)
    {
        var result = await SysUserService.ResetPwdAsync(item);
        await Toast!.Success("重置密码", $"操作{(result ? "成功" : "失败")}。");
    }

    private async Task OnOwnRoleAsync(UserOutput item)
    {
        _ownRoles = await SysUserService.OwnRoleAsync(_allRoles,item);
        await DialogService.Show(new DialogOption()
        {
            Title = "授权角色",
            IsCentered = true,
            ShowFooter = true,
            ShowSaveButton = true,
            OnSaveAsync = (async () =>
            {
                var ids = _ownRoles?.Select(x => x.Id);
                var result = await SysUserService.GrantRoleAsync(ids, item);
                await Toast!.Success("授权角色", $"操作{(result ? "成功" : "失败")}。");
                return result;
            }),
            BodyTemplate = 
    @<Table TItem="RoleOutput" 
        IsMultipleSelect="true" 
        ClickToSelect="true" 
        Items="_allRoles"
        @bind-SelectedRows="_ownRoles">
        <TableColumns>
            <TableColumn @bind-Field="@context.Name" />
            <TableColumn @bind-Field="@context.Code" />
        </TableColumns>
    </Table>
    });
    }

    private async Task OnOwnDataAsync(UserOutput item)
    {
        await SysUserService.OwnDataAsync(_allOrgs, item);
        await DialogService.Show(new DialogOption()
            {
                Title = "授权数据",
                IsCentered = true,
                ShowFooter = true,
                ShowSaveButton = true,
                OnSaveAsync = (async () =>
                {
                    var ids = _allOrgs.GetCheckedKeys<long>();
                    var result = await SysUserService.GrantDataAsync(ids, item);
                    await Toast!.Success("授权数据", $"操作{(result ? "成功" : "失败")}。");
                    return result;
                }),
                BodyTemplate =@<Scroll Height="480px"><Tree Items=@_allOrgs ShowCheckbox="true"/></Scroll>
            });
    }

    private async Task OnOrgTreeItemClick(TreeItem item)
    {
        if (item.Key != null)
        {
            _selectOrg = item.Key.ToString();
            await _table!.QueryAsync();
        }
    }
}